<template>
  <div id="indexMap-map" style="width:100%;height:658px;"></div>
</template>
<script>
import '@/assets/map/ol/ol.css';
import { getProjection } from "@/map/projMap.js";
import Map from 'ol/Map';
import View from 'ol/View';
import VectorLayer from 'ol/layer/Vector';
import {Vector as VectorSource} from 'ol/source';
import WKT from 'ol/format/WKT';
import {boundingExtent} from 'ol/extent';
import {Fill, Stroke, Style, Icon, Circle as CircleStyle,Text} from 'ol/style';
import dingweiImg from '@/assets/map/image/newImage/blueMarker.png';

export default {
  name: "IndexMap",
  components: {

  },
  props:{
    resultDialogType: {//计算结果类型
      type:String,
      required:false,
      default: ""
    },
    resultDataList: {//计算结果数据列表
      type:Array,
      required:false,
      default: []
    },
    drawXzqhGeom: {//地图圈选和行政区划选择空间数据
      type:String,
      required:false,
      default: ""
    },
    resultLegendList: {//计算结果图例数组
      type:Array,
      required:false,
      default: []
    },
  },
  emits:["getMap"],
  data() {
    return {
      str: "indexMap",
      map: null,
      center: [105, 34],
      zoom: 4,
      resultDataLayer:null,//计算结果图层
      allDataList:null,//计算结果数据列表
      drawXzqhGeomText:"",//地图圈选和行政区划选择空间数据
      drawXzqhGeomLayer:null,//地图圈选和行政区划选择空间数据图层
      resultLegendArray:[],//计算结果图例数组
      resultType:null,//计算结果类型
    }
  },
  watch: {
    resultDialogType: {//计算结果类型
      handler: function(newVal,oldVal){
        if(newVal!=oldVal){
          this.resultType = newVal;
        }
      },
      immediate:true
    },
    resultDataList: {//计算结果数据列表
      handler: function(newVal,oldVal){
        if(newVal!=oldVal){
          this.allDataList = newVal;
          let that = this;
          //异步加载
          setTimeout(() => {
            //显示计算结果数据列表
            that.showResultDataList();
          }, 500);
        }
      },
      immediate:true
    },
    drawXzqhGeom: {//地图圈选和行政区划选择空间数据
      handler: function(newVal,oldVal){
        if(newVal!=oldVal){
          this.drawXzqhGeomText = newVal;
          //显示地图圈选和行政区划选择空间数据
          this.showDrawXzqhGeomText();
        }
      },
      immediate:true
    },
    resultLegendList: {//计算结果图例数组
      handler: function(newVal,oldVal){
        if(newVal!=oldVal){
          this.resultLegendArray = newVal;
        }
      },
      immediate:true
    },
  },
  created() {

  },
  mounted() {
    console.log("mounted");
    let that = this;
    //地图异步加载
    this.$nextTick(function(){
      console.log('地图异步加载');
      //地图异步加载
      setTimeout(() => {
        //初始化地图信息
        that.initMap();
        //显示地图圈选和行政区划选择空间数据
        that.showDrawXzqhGeomText();
        //显示计算结果数据列表
        that.showResultDataList();
      }, 200);
    });
  },
  beforeCreate() {//生命周期创建之前
    console.log("beforeCreate");
  },
  beforeMount() {//生命周期挂载之前
    console.log("beforeMount");
  },
  beforeUpdate() {//生命周期更新之前
    console.log("beforeUpdate");
  },
  updated() {//生命周期更新之后
    console.log("updated");
  },
  beforeDestroy() {//生命周期销毁之前
    console.log("beforeDestroy");
  },
  destroyed() {//生命周期销毁完成
    this.map = null;
    console.log("销毁地图");
  },
  activated() {//如果页面有keep-alive缓存功能激活，这个函数会触发
    console.log("activated-"+this.str);
    //自动获取地图div高度
    this.autodivheight();
    //浏览器窗口发生变化时同时变化DIV高度
    window.onresize=this.autodivheight;
  },
  deactivated() {//如果页面有keep-alive缓存功能停用，这个函数会触发
    console.log("deactivated-"+this.str);
    //取消浏览器窗口发生变化时同时变化DIV高度事件
    window.onresize = null;
  },
  methods: {
    initMap() {
      let that = this;
      let mapStr = this.str;
      let targetMap = document.getElementById(mapStr+"-map");
      if(targetMap.innerHTML!=""){
        console.log("清空targetMap");
      }
      targetMap.innerHTML = "";//清空
      //自动获取地图div高度
      this.autodivheight();
      //浏览器窗口发生变化时同时变化DIV高度
      window.onresize=this.autodivheight;
      if(this.map){//避免重复加载地图
        console.log("避免重复加载地图");
        return;
      }
      console.log("初始化地图");
      //获取投影4490坐标系
      this.projection4490 = getProjection();
      //初始化地图信息
      this.map = new Map({
        target: targetMap.id,
        /*controls: defaultControls({attributionOptions: {collapsed: false}})
            .extend([new Logo()]),*/
        view: new View({
          center: this.center,
          maxZoom: 18,
          minZoom: 4,
          zoom: this.zoom,
          constrainResolution:true,//缩放地图可移动到最近的缩放级别（整数zoom级别）
          projection: 'EPSG:4490',
          // resolutions:getResolutions()
        })
      });
      console.log("this.map");
      console.log(this.map);

      //计算结果图层
      this.resultDataLayer = new VectorLayer({
        source: new VectorSource({
          wrapX: false
        }),
        projection: 'EPSG:4490'
      });
      this.map.addLayer(this.resultDataLayer);
      this.resultDataLayer.setZIndex(8);

      //地图圈选和行政区划选择空间数据图层
      this.drawXzqhGeomLayer = new VectorLayer({
        source: new VectorSource({
          wrapX: false
        }),
        projection: 'EPSG:4490'
      });
      this.map.addLayer(this.drawXzqhGeomLayer);
      this.drawXzqhGeomLayer.setZIndex(8);

      //地图对象传递
      this.$emit("getMap",this.map);
    },
    autodivheight() {//自动获取div高度
      //获取浏览器窗口高度
      let winHeight = 0;
      if (window.innerHeight) {
        winHeight = window.innerHeight;
      } else if ((document.body) && (document.body.clientHeight)) {
        winHeight = document.body.clientHeight;
      }
      //通过深入Document内部对body进行检测，获取浏览器窗口高度
      if (document.documentElement && document.documentElement.clientHeight) {
        winHeight = document.documentElement.clientHeight;
      }
      //全屏时窗口高度:864px,地图div高度:754px
      let tempHeight = 864;
      let mapTempHeight = 754;
      let mapHeight = winHeight - tempHeight + mapTempHeight;
      //最小高度
      if(mapHeight<480){
        mapHeight = 480;
      }
      //设置地图高度
      document.getElementById(this.str+"-map") && (document.getElementById(this.str+"-map").style.height= mapHeight +"px")
      console.log("窗口高度："+winHeight+"地图高度："+mapHeight);
      //resize事件--刷新地图,确保地图不变形
      if(this.map){
        this.map.updateSize();
        console.log("resize事件--刷新地图,确保地图不变形");
      }
    },
    getPointStyle(){// 点图标样式
      let style = new Style({
        image: new Icon({
          src: dingweiImg,
          anchor: [0.5, 1]
        }),
      });
      return style;
    },
    getPolyonStyle(color,fillColor,width){//多边形样式
      if(fillColor!=null){
        //填充样式
      }else{
        fillColor = "rgba(0,0,0,0)";
      }
      if(width!=null){
        //线宽度
      }else{
        width = 2;
      }
      let style = new Style({
        fill:new Fill({//填充样式
          color:fillColor
        }),
        stroke:new Stroke({//描绘
          width:width,//宽
          color:color
        }),
        zIndex: 100
      });
      return style;
    },
    getSelectPolyonStyle(){//选中要素样式
      let style = new Style({
        fill:new Fill({//填充样式
          color:"rgba(255,255,255,0.2)"
        }),
        stroke:new Stroke({//描绘
          width:2,//宽
          color:"rgba(30,144,255,1)"
        })
      });
      return style;
    },
    showBoundingExtent(coordinates){//缩放到区域位置
      console.log("缩放到区域位置");
      if (coordinates!=null && coordinates.length > 1) {
        const extent = boundingExtent(coordinates);
        //this.map.getView().fit(extent, {duration: 1000, padding: [50, 50, 50, 50]});
        this.map.getView().fit(extent, {padding: [50, 50, 50, 50]});
        //获取默认位置
        this.center = this.map.getView().getCenter();
        this.zoom = this.map.getView().getZoom();
      }
    },
    //显示计算结果数据列表
    showResultDataList(){
      console.log("计算结果数据列表");
      return;//不显示计算结果图层，直接用超图图层展示
      if(this.resultDataLayer!=null){
        this.resultDataLayer.getSource().clear();//清空
        let list = this.allDataList;
        console.log(list);
        if(list!=null && list.length>0){
          //全部经纬度
          let allCoordinates = [];
          for(let i=0;i<list.length;i++){
            let fillColor = this.getFillColorByValue(list[i]);//获取计算结果填充颜色
            let style = this.getPolyonStyle("gray",fillColor,0.5);
            let geomText = list[i].geomText;
            if(geomText!=null && geomText!="" && geomText!="POLYGON EMPTY"){
              //空间数据
              let featureTmp = new WKT().readFeature(geomText);
              //设置属性
              featureTmp.setProperties({
                type:"result",//类型
              });
              featureTmp.setStyle(style);
              //添加矢量数据
              this.resultDataLayer.getSource().addFeature(featureTmp);
              //获取范围
              let extent = featureTmp.getGeometry().getExtent();
              if(extent.length==4){
                //全部经纬度--左下角
                allCoordinates.push([extent[0],extent[1]]);
                //全部经纬度--右上角
                allCoordinates.push([extent[2],extent[3]]);
              }
            }
          }
          this.showBoundingExtent(allCoordinates);//缩放到区域位置
        }
      }
    },
    //获取计算结果填充颜色
    getFillColorByValue(obj){
      let fillColor = null;
      let type = this.resultType;
      let val = "";
      if(type=="与地震烈度的关系"){
        val = obj.intensity;//烈度
      }else if(type=="与距断层距离的关系"){
        val = obj.faultRange;//距断层的距离。7,>30;6,25~30;5,20~25;4,15~20;3,10~15;2,5~10;1,0~5
      }else if(type=="与高程的关系"){
        val = obj.teraRange;//高程。1,<0.6;2,0.6~1;3,1~1.5;4,1.5~2;5,2~2.5;6,2.5~3;7,3~3.5;8,>3.5
      }else if(type=="与地形坡度的关系"){
        val = obj.slopeRange;//坡度。1,<15;2,15~25;3,25~35;4,35~45;5,45~55;6,>55
      }else if(type=="与坡向的关系"){
        val = obj.aspectRange;//坡向1,N;2,NE;3,E;4,ES;5,S;6,SW;7,W;8,WN
      }else if(type=="与水系的关系"){
        val = obj.drainageRange;//距水系距离。1,0~500;2,500~1000;3,1000~1500;4,1500~2000;5,>2000
      }else if(type=="与地层岩性的关系"){
        val = obj.lithologyRange;//地层岩性。1,Q4;2,Er;3,T3z;4,T3zh;5,T2zg;6,T1b;7,Tγo;8,P2b-d;9,Psd-d;10,C2h;11,Cz-h;12,D2y
      }
      if(val && this.resultLegendArray && this.resultLegendArray.length>0){
        for(let i=0;i<this.resultLegendArray.length;i++){
          if(this.resultLegendArray[i].value==val){
            fillColor = this.resultLegendArray[i].color;
            break;
          }
        }
      }

      return fillColor;
    },
    //显示地图圈选和行政区划选择空间数据
    showDrawXzqhGeomText(){
      let that = this;
      if(this.drawXzqhGeomLayer!=null) {
        this.drawXzqhGeomLayer.getSource().clear();//清空
        if(this.drawXzqhGeomText){
          let style = this.getPolyonStyle("orange",null,null);
          let geomText = this.drawXzqhGeomText;
          //空间数据
          let featureTmp = new WKT().readFeature(geomText);
          //设置属性
          featureTmp.setProperties({
            type:"draw",//类型
          });
          featureTmp.setStyle(style);
          //添加矢量数据
          this.drawXzqhGeomLayer.getSource().addFeature(featureTmp);
          //全部经纬度
          let allCoordinates = [];
          //获取范围
          let extent = featureTmp.getGeometry().getExtent();
          if(extent.length==4){
            //全部经纬度--左下角
            allCoordinates.push([extent[0],extent[1]]);
            //全部经纬度--右上角
            allCoordinates.push([extent[2],extent[3]]);
          }
          //延迟
          setTimeout(function(){
            that.showBoundingExtent(allCoordinates);//缩放到区域位置
          },500);
        }
      }
    },
  }
}

</script>

<style lang="scss" scoped>

</style>